<?php


//check request from cli
if (php_sapi_name() === 'cli') {
	
	$directoriesArray = array(
		'photos_immuno',
		'photos_induction',
		'photos_irm',
		
	);
	
	$filesToSendArray = array();
	
	$data_dir = dirname(__FILE__);
	
	require_once $data_dir."/../includes/config.php";
	require_once $data_dir.'/GDrive.php';
	require_once $data_dir."/../classes/PHPMailer/PHPMailerAutoload.php";
	
	
	$backup_date = date("Ymd_Hs");
	
	$dumpFileName = $data_dir . "/"."dump_" . $backup_date . ".sql";
	
	$dumpCommand = "export PGUSER=".USER." && export PGPASSWORD=".PASSWORD." && ";
	$dumpCommand .= PGDUMP_EXEC_FILE_PATH." -CO --inserts --host ".HOST." --port ".DB_PORT." ".DBNAME." --file ".$dumpFileName;
	$dumpCommand .= " && unset PGPASSWORD && unset PGUSER";
	
	$message = system($dumpCommand);
	$filesToSendArray[] = $dumpFileName;
	
	$zipFileName = $data_dir."/images_".$backup_date.".zip";
	
	foreach ($directoriesArray as $directory) {
		$zipCommand = "zip -r ".$zipFileName." ".$data_dir."/../".$directory."/";
		$message = system($zipCommand);
	}
	
	$filesToSendArray[] = $zipFileName;
	
	$gdriveStatusArray = GDrive::sendBackupFiles($filesToSendArray, "backup_{$backup_date}");
	
	var_dump($gdriveStatusArray);
	
	foreach ($filesToSendArray as $fileToRemove) {
		unlink($fileToRemove);
	}
	
	$backupFolderURI = $gdriveStatusArray['alternateLink'];
	
	$mail = new PHPMailer;
	
	$mail->isSMTP();                                      // Set mailer to use SMTP
	$mail->Host = SMTP_HOST;  // Specify main and backup server
	//$mail->SMTPAuth = true;                               // Enable SMTP authentication
	$mail->Username = SENDER_EMAIL;                            // SMTP username
	$mail->Password = SENDER_PASSWORD;                           // SMTP password
	
	$mail->From = SENDER_EMAIL;
	$mail->FromName = SENDER_NAME;
	$mail->addAddress(ADMINISTATOR_EMAIL, ADMINISTATOR_NAME);  // Add a recipient
	$mail->addReplyTo(REPLY_TO_EMAIL, REPLY_TO_NAME);
	
	$mail->WordWrap = 50;                                 // Set word wrap to 50 characters
	$mail->isHTML(true);                                  // Set email format to HTML
	
	$mail->Subject = 'Backup database acaccomplished';
	$bodyMessage = 'Backup mmdn database ['.date("d/m/Y H:i:s").']';
	$mail->Body = $bodyMessage.'<br/><a href="'.$backupFolderURI.'">'.$backupFolderURI.'</a>';
	$mail->AltBody = $bodyMessage.' '.$backupFolderURI;
	
	if(!$mail->send()) {
	echo 'Message could not be sent.';
	echo 'Mailer Error: ' . $mail->ErrorInfo;
	exit;
	}
	
	echo 'Message has been sent';
}